package cn.com.manager.filter;

import cn.com.manager.utility.ApplicationConstants;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheManager;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.SessionManager;
import org.apache.shiro.session.mgt.eis.SessionDAO;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authz.AuthorizationFilter;
import org.apache.shiro.web.util.WebUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Administrator on 2016/4/19.
 */
public class LogoutControllerFilter extends AuthorizationFilter {
    private String kickoutUrl;
    private Cache<Serializable,Session> cache;

    public void setKickoutUrl(String kickoutUrl) {
        this.kickoutUrl = kickoutUrl;
    }

    public void setCache(Cache<Serializable, Session> cache) {
        this.cache = cache;
    }

    public LogoutControllerFilter(CacheManager cacheManager) {
        this.cache = cacheManager.getCache("sessionManagerCache");
    }

    @Override
    protected boolean isAccessAllowed(ServletRequest servletRequest, ServletResponse servletResponse, Object o) throws Exception {
        Subject subject = getSubject(servletRequest, servletResponse);
        Session session = subject.getSession();
        return session.getAttribute(ApplicationConstants.SESSION_LOGOUT) == null;
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws IOException {
        try{
            Subject subject = getSubject(request, response);
            Session session = subject.getSession();
            subject.logout();
            saveRequest(request);
            Map<String,Object> param = new HashMap<>();
            param.put("kickout","账号被强制退出，请重新登录！");
            WebUtils.issueRedirect(request,response,kickoutUrl,param);
        }catch(Exception e){
        }
        return false;
    }
}
